package org.me.nyx.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.me.nyx.data.DataAdapter;
import org.me.nyx.domain.Movie;

public class MovieLoader implements Runnable {
    private static final String SERVER_URL = "http://192.168.67.174/nyx.json";
	private DataAdapter<Movie> adapter;
	
    public MovieLoader(DataAdapter<Movie> adapter){
		this.adapter = adapter;
    }

    public void run() {
		String data = "";
		try {
			URL url = new URL(SERVER_URL);
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
			String str;
			while ((str = in.readLine()) != null) {
				data += str;
			}
			in.close();
		}
		catch (MalformedURLException e) { }
		catch (IOException e) { }

		ArrayList<Movie> list = new ArrayList<Movie>();
		try {
			JSONObject obj = new JSONObject(data);
			JSONArray array = obj.getJSONArray("Movies");
			for (int i = 0; i < array.length(); i++)
			{
				JSONObject m = array.getJSONObject(i);
				Movie movie = new Movie(m.getString("Name"));
				movie.setRating(m.getDouble("Rating"));
				movie.setDescription(m.getString("Description"));
				list.add(movie);
			}
		} catch (JSONException ex) { }

		Object[] array = list.toArray();
		Arrays.sort(array, new Comparator<Object>() {
			public int compare(Object a, Object b) {
				return ((Movie)a).getName().toLowerCase().
					compareTo(((Movie)b).getName().toLowerCase());
			}
		});

		Movie.list = new ArrayList<Movie>();
		for (Object o : array)
			Movie.list.add((Movie)o);

		adapter.setData(Movie.list);
    }
}
